import { StyleSheet, Text, View, ScrollView, Pressable, Image, Linking } from 'react-native';
import React, { useState, useCallback, useRef, useMemo } from 'react';
import { useRoute, useFocusEffect, useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import { useTranslation } from 'react-i18next';
import { NavBarHeader, MyLoading } from '~/components';
import { onePx, px2dp, scale } from '~/utils/px2dp';
import { getUserDeviceListByDoctor } from '~/api/doctor';
import { getAge } from '~/utils/formatDate';
import { observer, webSocketStore } from '~/store';
import { getDeviceStatus } from '~/utils/socketMessenger';
import { useAddMessage } from '~/common';

export default observer(() => {
    const { t } = useTranslation();
    const router: any = useRoute();
    const navigation: any = useNavigation();
    const { userInfo = {} } = router.params || {};
    const [listData, setListData] = useState<any>([]);
    const { device_online } = webSocketStore;
    const loadingRef = useRef<any>();

    const data = [
        {
            id: 1,
            name: t('AddDeviceScreen.t15'),
            user_id: '',
            device_id: '',
            body_index: 1,
            armarium_device_chang: '',
            course_id: '',
            status: 0,
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
            user_course_id: '',
        },
        {
            id: 2,
            name: t('AddDeviceScreen.t16'),
            user_id: '',
            device_id: '',
            body_index: 2,
            armarium_device_chang: '',
            course_id: '',
            status: 0,
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
            user_course_id: '',
        },
        {
            id: 3,
            name: t('AddDeviceScreen.t17'),
            user_id: '',
            device_id: '',
            body_index: 3,
            armarium_device_chang: '',
            course_id: '',
            status: 0,
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
            user_course_id: '',
        },
        {
            id: 4,
            name: t('AddDeviceScreen.t18'),
            user_id: '',
            device_id: '',
            body_index: 4,
            armarium_device_chang: '',
            course_id: '',
            status: 0,
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
            user_course_id: '',
        },
        {
            id: 5,
            name: t('AddDeviceScreen.t19'),
            user_id: '',
            device_id: '',
            body_index: 5,
            armarium_device_chang: '',
            course_id: '',
            status: 0,
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
            user_course_id: '',
        },
    ];

    const getData = () => {
        getUserDeviceListByDoctor({ user_id: userInfo.user_id }).then((res) => {
            if (res.list.length > 0) {
                const updatedList = data.map((itemB) => {
                    const matchedItem = res.list.find((itemA) => itemA.body_index == String(itemB.body_index)); // body_index 转换成字符串
                    if (matchedItem) {
                        return {
                            ...itemB,
                            id: matchedItem.id || itemB.id,
                            armarium_device_chang: matchedItem.armarium_device_chang || '',
                            course_id: matchedItem.course_id || '',
                            device_id: matchedItem.device_id || '',
                            device_image: matchedItem.device_image || itemB.device_image,
                        };
                    }
                    return itemB;
                });

                setListData(updatedList);
            } else {
                setListData(data);
            }
        });
    };
    // 查看详情
    const goDeviceDetailes = (item) => {
        navigation.navigate('DoctorDeviceDetailes', {
            user_id: userInfo.user_id,
            device_sn: item.armarium_device_chang,
            course_id: item.course_id,
            pupillus_mobile: userInfo.armarium_science_user_mobile,
        });
    };
    const callDevice = () => {
        if (device_online == 0) {
            Toast.show({ content: t('DoctorDeviceDetailes.t1'), layout: 'top' });
            return;
        }
        const params = {
            device_sn: userInfo?.armarium_device_chang,
            user_name: userInfo.armarium_science_user_name || '用户',
            to_uid: userInfo.user_id,
            fo_type: 5,
        };
        navigation.navigate('CallDevice', params);
    };
    useFocusEffect(
        useCallback(() => {
            getDeviceStatus(userInfo.armarium_device_chang); // 获取设备状态
            getData();
        }, []),
    );
    // const callPhone = () => {
    //     Linking.openURL(`tel:${userInfo?.armarium_science_user_mobile}`);
    // };
    const isDeviceSnEmpty = useMemo(
        () =>
            listData.some((item: any) => {
                return !item.armarium_device_chang;
            }),
        [listData],
    );
    const goDeviceDataWebView = () => {
        if (isDeviceSnEmpty) {
            Toast.show({ content: t('doctor.t8'), layout: 'top' });
            return;
        }
        const newArray = listData.map((item, index) => {
            return { course_id: item.course_id, device_id: item.device_id };
        });
        navigation.navigate('DeviceDataWebView', {
            category: 'acupoint',
            acupointParams: JSON.stringify(newArray),
            userId: userInfo.user_id,
            type: 'doctor',
        });
    };
    const createMessage = () => {
        navigation.navigate('DoctorVoiceList', {
            device_sn: userInfo?.armarium_device_chang,
            user_id: userInfo.user_id,
            actionType: 'doctor',
        });
    };
    // 消息提示
    const { addMessage, loading, error } = useAddMessage();
    const addMess = async (row) => {
        loadingRef.current.showLoading();
        try {
            const response = await addMessage({
                type: 5,
                title: t('doctor.t10'),
                content: `${row.name}${t('doctor.t11')}`,
                user_id: userInfo.user_id,
            });
            loadingRef.current.hideLoading();
            if (response.message == 'ok') {
                Toast.show({ content: t('doctor.t9'), layout: 'top' });
            } else {
                Toast.show({ content: response.message, layout: 'top' });
            }
        } catch (err) {
            loadingRef.current.hideLoading();
        }
    };
    return (
        <View style={styles.container}>
            <NavBarHeader title={t('doctor.t6')} />
            <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.contentStyle}>
                {/* 功能栏 */}
                <View style={[styles.row, styles.between, styles.menue]}>
                    <Pressable style={styles.center} onPress={goDeviceDataWebView}>
                        <Image
                            resizeMode="contain"
                            style={styles.icons}
                            source={{
                                uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/03/471c9202503061522581021.png',
                            }}
                        />
                        <Text style={styles.menue_title}>{t('doctor.t12')}</Text>
                    </Pressable>
                    {/* <Pressable
                        style={styles.center}
                        onPress={() => Toast.show({ content: t('Acupoints.t54'), layout: 'top' })}>
                        <Image
                            resizeMode="contain"
                            style={styles.icons}
                            source={{
                                uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/03/17f80202503061528223681.png',
                            }}
                        />
                        <Text style={styles.menue_title}>{t('doctor.t14')}</Text>
                    </Pressable> */}
                    <Pressable style={styles.center} onPress={callDevice}>
                        <Image
                            resizeMode="contain"
                            style={styles.icons}
                            source={{
                                uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/912bd202502281147514953.png',
                            }}
                        />
                        <Text style={styles.menue_title}>{t('doctor.t13')}</Text>
                    </Pressable>
                    {/* <Pressable style={styles.center} onPress={createMessage}>
                        <Image
                            resizeMode="contain"
                            style={styles.icons}
                            source={{
                                uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2023/11/f05af202311161042048960.png',
                            }}
                        />
                        <Text style={styles.menue_title}>{t('doctor.t15')}</Text>
                    </Pressable> */}
                    <View style={styles.center}></View>
                </View>
                {/* 用户信息 */}
                <View style={[styles.row, styles.menue]}>
                    <Image
                        resizeMode="contain"
                        style={styles.avatar}
                        source={{
                            uri: userInfo?.wx_head_portrait
                                ? userInfo?.wx_head_portrait
                                : 'https://bjy.oss-cn-shenzhen.aliyuncs.com/pic/20230413/3041681348866.png',
                        }}
                    />
                    <View style={{ marginLeft: px2dp(24) }}>
                        <Text style={styles.userName}>{userInfo?.armarium_science_user_name || t('doctor.t16')}</Text>
                        <View style={styles.row}>
                            {/* <Pressable style={styles.row} onPress={callPhone}>
                                <Image
                                    style={styles.icons1}
                                    source={{
                                        uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2023/11/4e62d202311061625351306.png',
                                    }}
                                />
                                <Text style={styles.t1}>{userInfo.armarium_science_user_mobile}</Text>
                            </Pressable> */}
                            <View style={[styles.row, { marginLeft: px2dp(32) }]}>
                                <Image
                                    style={styles.icons1}
                                    source={{
                                        uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/cfd3d202502221525008152.png',
                                    }}
                                />
                                <Text style={styles.t1}>{getAge(userInfo.armarium_science_user_birthday)}</Text>
                            </View>
                        </View>
                    </View>
                </View>
                {/* YY01信息 */}
                <Pressable
                    style={[styles.row, styles.menue]}
                    onPress={() =>
                        navigation.navigate('DoctorDeviceDetailes', {
                            device_sn: userInfo?.armarium_device_chang,
                            course_id: 0,
                        })
                    }>
                    <Image
                        resizeMode="contain"
                        style={styles.device_Icons}
                        source={{
                            uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/ac25e20250224170209347.png',
                        }}
                    />
                    <View style={{ marginLeft: px2dp(24) }}>
                        <View style={styles.row}>
                            <Text style={styles.userName}>{userInfo?.armarium_device_chang}</Text>
                            <View style={[styles.active_border, device_online == 0 && { backgroundColor: '#e8e8e8' }]}>
                                <Text style={[styles.active_border_text, device_online == 0 && { color: '#a4a4a4' }]}>
                                    {device_online == 1 ? t('doctor.t17') : t('doctor.t18')}
                                </Text>
                            </View>
                        </View>
                        <Text style={styles.t1}>
                            {t('doctor.t19')} {'>'}
                        </Text>
                    </View>
                </Pressable>
                {/* 穴位手表 */}
                <View style={[styles.menue]}>
                    {listData.map((item, index) => {
                        return (
                            <Pressable
                                key={item.id}
                                style={[styles.row, styles.listItem, styles.between]}
                                onPress={() => {
                                    if (item.armarium_device_chang) {
                                        goDeviceDetailes(item);
                                    }
                                }}>
                                <View style={[styles.row]}>
                                    <Image
                                        resizeMode="contain"
                                        style={styles.device_images}
                                        source={{ uri: item.device_image }}
                                    />
                                    <View>
                                        <View style={[styles.row]}>
                                            <Text style={styles.device_sn}>
                                                {item.armarium_device_chang ? item.armarium_device_chang : '—'}
                                            </Text>
                                            {item.armarium_device_chang && (
                                                <View style={[styles.active_border]}>
                                                    <Text style={[styles.active_border_text]}>{t('doctor.t20')}</Text>
                                                </View>
                                            )}
                                        </View>
                                        <Text style={styles.name}>{item.name}</Text>
                                    </View>
                                </View>
                                {!item.armarium_device_chang ? (
                                    <Pressable style={styles.bt} onPress={() => addMess(item)}>
                                        <Text style={styles.btText}>{t('doctor.t21')}</Text>
                                    </Pressable>
                                ) : (
                                    <View>
                                        <Icon name={'chevron-forward-outline'} size={px2dp(40)} color={'#eee'}></Icon>
                                    </View>
                                )}
                            </Pressable>
                        );
                    })}
                </View>
            </ScrollView>
            <MyLoading ref={loadingRef} />
        </View>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    center: {
        justifyContent: 'center',
        alignItems: 'center',
    },
    container: {
        flex: 1,
    },
    contentStyle: {
        flexGrow: 1,
        paddingBottom: '30%',
    },
    menue: {
        backgroundColor: '#fff',
        marginHorizontal: px2dp(24),
        padding: px2dp(24),
        marginTop: px2dp(24),
        borderRadius: px2dp(12),
    },
    icons: {
        width: px2dp(80),
        height: px2dp(80),
        marginBottom: px2dp(8),
    },
    icons1: {
        width: px2dp(30),
        height: px2dp(30),
        marginRight: px2dp(12),
    },
    menue_title: {
        color: '#4C4C4C',
        fontSize: scale(24),
    },
    avatar: {
        width: px2dp(120),
        height: px2dp(120),
    },
    userName: {
        color: '#1A1A1A',
        fontSize: scale(32),
        fontWeight: 'bold',
        marginBottom: px2dp(12),
    },
    t1: {
        color: '#626262',
        fontSize: scale(24),
    },
    device_Icons: {
        width: px2dp(120),
        height: px2dp(120),
    },
    active_border: {
        backgroundColor: 'rgba(29, 206, 135, 0.12)',
        borderRadius: px2dp(12),
        marginLeft: px2dp(24),
        paddingHorizontal: px2dp(12),
        paddingVertical: px2dp(8),
        marginBottom: px2dp(12),
    },
    active_border_text: {
        color: '#1DCE87',
        fontSize: scale(24),
    },
    device_images: {
        width: px2dp(100),
        height: px2dp(100),
    },
    listItem: {
        borderBottomWidth: onePx,
        borderColor: '#eee',
        paddingVertical: px2dp(24),
    },
    device_sn: {
        color: '#000',
        fontWeight: '500',
        fontSize: scale(28),
        marginBottom: px2dp(24),
    },
    name: {
        color: '#a6a6a6',
        fontSize: scale(24),
    },
    bt: {
        backgroundColor: '#1A76FF',
        paddingHorizontal: px2dp(22),
        paddingVertical: px2dp(12),
        borderRadius: px2dp(50),
    },
    btText: {
        color: '#fff',
        fontSize: scale(26),
    },
});
